//
//  HNVMainuUserListiController.m
//  XDEducation
//
//  Created by 星道 on 17/5/25.
//  Copyright © 2017年 apple. All rights reserved.
//

#import "HNVMainuUserListiController.h"
#import "HNMainuUserListPersonModel.h"
#import "HNMainuUserListGuiJuModel.h"
#import "HNMainUserListGuiJuCellTableViewCell.h"

@interface HNVMainuUserListiController ()<UITableViewDelegate,UITableViewDataSource>
@property (nonatomic, weak) UIButton *TempButton_Person;
@property (nonatomic, weak) UIButton *TempButton_Top;
@property (nonatomic, strong) UIScrollView *ScrollView;
@property (nonatomic, strong) NSMutableArray *DataArr_Person;
@property (nonatomic, strong) NSMutableArray *DataArr_GuiJu;
@property (nonatomic, strong) UITableView *TableView;
@property (nonatomic, strong) NSArray *Type_GuiJu;
@property (nonatomic, strong) UIButton *AddGuiJuButton;
@end

@implementation HNVMainuUserListiController

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.view.backgroundColor = UIColor(240, 240, 240);
    




        [self LeftPersonRefreshDataWithComplete:^{

            dispatch_async(dispatch_get_main_queue(), ^{

                [self UI];
                [self RightContentRefreshDataWithComplete:^{

                }];
            });
        }];


}





#pragma mark - UI
- (void)UI
{
    [self.view addSubview:self.ScrollView];
    [self.view addSubview:[self TopButtonView]];
    [self.view addSubview:self.TableView];
    
    for (int i=0; i<self.DataArr_Person.count; i++)
    {
        HNMainuUserListPersonModel *Model = self.DataArr_Person[i];
        UIButton *Button = [self GetLeftButtonWithTitle:Model.nickname Frame:CGRectMake(0, i*54, self.ScrollView.frame.size.width, 54)];
        [self.ScrollView addSubview:Button];
        
        if (i == 0)
        {
            Button.selected = YES;
            self.TempButton_Person = Button;
        }
        
        if (i == self.DataArr_Person.count-1)
        {
            self.ScrollView.contentSize = CGSizeMake(70, Button.frame.size.height+Button.frame.origin.y);
        }
    }
}











#pragma mark - 网络请求
/** 左侧人物请求 */
- (void)LeftPersonRefreshDataWithComplete:(void(^)())Complete
{
    [MBProgressHUD showHUD];
    [XDHttpTool get:BaseURL(@"family.do?action=mainuuserlist") authCode:[AccountTool shareAccountTool].currentAccount.authCode params:@{@"uid":[AccountTool shareAccountTool].currentAccount.uid} success:^(id responseObj) {
        
        if ([responseObj isKindOfClass:[NSArray class]])
        {
            for (NSDictionary *Dict in responseObj)
            {
                [self.DataArr_Person addObject:[[HNMainuUserListPersonModel alloc] init_HNObjectWithDict:Dict]];
            }
            Complete ();
        }
        else
        {
            [MBProgressHUD showError:responseObj[@"data"][@"msg"]];
        }
        
    } failure:^(NSError *error) {
        
        [MBProgressHUD showError:XDNetWorkError];
    }];
}

//中国观、家风、家规
- (void)RightContentRefreshDataWithComplete:(void(^)())Complete
{
    NSNumber *UID = nil;
    NSNumber *Index = nil;
    for (HNMainuUserListPersonModel *Model in self.DataArr_Person)
    {
        if ([self.TempButton_Person.titleLabel.text isEqualToString:Model.nickname])
        {
            UID = Model.uid;
            break;
        }
    }
    
    for (NSDictionary *Dict in self.Type_GuiJu)
    {
        if ([self.TempButton_Top.titleLabel.text isEqualToString:Dict[@"name"]])
        {
            Index = Dict[@"type"];
            break;
        }
    }
    NSDictionary *Params = @{@"uid":UID,
                             @"type":Index
                             };
    [XDHttpTool get:BaseURL(@"family.do?action=getrules") authCode:[AccountTool shareAccountTool].currentAccount.authCode params:Params success:^(id responseObj) {
        
        [self.DataArr_GuiJu removeAllObjects];
        [self.TableView reloadData];
        if ([responseObj isKindOfClass:[NSArray class]])
        {
            [self.DataArr_GuiJu removeAllObjects];
            for (NSDictionary *Dict in responseObj)
            {
                [self.DataArr_GuiJu addObject:[[HNMainuUserListGuiJuModel alloc] init_HNObjectWithDict:Dict]];
            }
            dispatch_async(dispatch_get_main_queue(), ^{
               [self.TableView reloadData];
            });
        }
        else
        {
            [MBProgressHUD showError:responseObj[@"data"][@"msg"]];
        }
    } failure:^(NSError *error) {
        [MBProgressHUD showError:XDNetWorkError];
    }];
}











#pragma mark - Fuc
/** 人物点击 */
- (void)SelectPerson:(UIButton *)Button
{
    for (HNMainuUserListPersonModel *Model in self.DataArr_Person)
    {
        if ([Button.titleLabel.text isEqualToString:Model.nickname])
        {
            self.TempButton_Person.selected = !self.TempButton_Person.selected;
            Button.selected = !Button.selected;
            self.TempButton_Person = Button;
            break;
        }
    }
    [self RightContentRefreshDataWithComplete:nil];


    [self.AddGuiJuButton removeFromSuperview];
    self.AddGuiJuButton = nil;
    CGRect Rect = self.TableView.frame;
    Rect.size.height += 44;
    self.TableView.frame = Rect;
    /** 当person为自己时,点击家风家规可以显示添加按钮 */
    //找出点击的人物是否为本人
    for (HNMainuUserListPersonModel *Model in self.DataArr_Person)
    {

        //找出后判断当前的sender是否不是中国规
        if ([Button.titleLabel.text isEqualToString:Model.nickname])
        {
            if (![self.TempButton_Top.titleLabel.text isEqualToString:@"中国规"] && [[Model.uid stringValue] isEqualToString:[AccountTool shareAccountTool].currentAccount.uid])
            {
                [self.view addSubview:self.AddGuiJuButton];
            }
            break;
        }
    }

}

/** 中国规、家风、家规点击 */
- (void)SelectGuiJu:(UIButton *)Button
{

    for (NSString *Str in [self TopGuiJu])
    {
        if ([Button.titleLabel.text isEqualToString:Str])
        {
            self.TempButton_Top.selected = !self.TempButton_Top.selected;
            Button.selected = !Button.selected;
            self.TempButton_Top = Button;
            break;
        }

    }
    [self RightContentRefreshDataWithComplete:nil];




    [self.AddGuiJuButton removeFromSuperview];
    self.AddGuiJuButton = nil;
    CGRect Rect = self.TableView.frame;
    Rect.size.height += 44;
    self.TableView.frame = Rect;
    /** 当person为自己时,点击家风家规可以显示添加按钮 */
    //找出点击的人物是否为本人
    for (HNMainuUserListPersonModel *Model in self.DataArr_Person)
    {

        //找出后判断当前的sender是否不是中国规
        if ([self.TempButton_Person.titleLabel.text isEqualToString:Model.nickname])
        {
            if (![Button.titleLabel.text isEqualToString:@"中国规"] && [[Model.uid stringValue] isEqualToString:[AccountTool shareAccountTool].currentAccount.uid])
            {
                [self.view addSubview:self.AddGuiJuButton];
            }
            break;
        }
    }
}


/** 颜色转图片 */
- (UIImage *)ImgForRGB:(CGSize)Size Color:(UIColor *)Color
{
    CGRect rect = CGRectMake(0, 0, Size.width, Size.height);
    UIGraphicsBeginImageContext(Size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetFillColorWithColor(context, Color.CGColor);
    CGContextFillRect(context, rect);
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return image;
}





/** 添加规矩 */
- (void)AddGuiJu:(UIButton *)Button
{
    NSNumber *Type = [[NSNumber alloc] init];
    NSString *Info = @"";

    if ([self.TempButton_Top.titleLabel.text isEqualToString:@"家规"])
    {
        Type = @3;
        Info = @"请输入家规";
    }
    else if ([self.TempButton_Top.titleLabel.text isEqualToString:@"家风"])
    {
        Type = @2;
        Info = @"请输入家风";
    }

    UIAlertController *Alert = [UIAlertController alertControllerWithTitle:Info message:nil preferredStyle:(UIAlertControllerStyleAlert)];
    [Alert addAction:[UIAlertAction actionWithTitle:@"添加" style:(UIAlertActionStyleDestructive) handler:^(UIAlertAction * _Nonnull action) {

        UITextField *TextFiles = [Alert.textFields firstObject];
        [MBProgressHUD showHUD];
        NSDictionary *Params = @{
                                 @"uid"     :[AccountTool shareAccountTool].currentAccount.uid,
                                 @"action"  :@"addrules",
                                 @"type"    :Type,
                                 @"content" :TextFiles.text
                                 };
        [XDHttpTool post:BaseURL(@"family.do?") authCode:[AccountTool shareAccountTool].currentAccount.authCode params:Params success:^(id responseObj) {

            if (responseObj)
            {
                [MBProgressHUD showHUD];
                [self RightContentRefreshDataWithComplete:nil];
            }
            else
            {
                [MBProgressHUD showError:responseObj[@"msg"]];
            }
        } failure:^(NSError *error) {
            [MBProgressHUD showError:XDNetWorkError];
        }];



    }]];
    [Alert addAction:[UIAlertAction actionWithTitle:@"取消" style:(UIAlertActionStyleCancel) handler:nil]];
    [Alert addTextFieldWithConfigurationHandler:^(UITextField * _Nonnull textField) {
        textField.placeholder = Info;
    }];
    [self presentViewController:Alert animated:YES completion:nil];
}








#pragma mark - 表单代理
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.DataArr_GuiJu.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    HNMainUserListGuiJuCellTableViewCell *Cell = [tableView dequeueReusableCellWithIdentifier:@"GuiJuCell" forIndexPath:indexPath];
    HNMainuUserListGuiJuModel *Model = self.DataArr_GuiJu[indexPath.row];
    HNMainuUserListPersonModel *PersonModelSub = nil;
    for (HNMainuUserListPersonModel *PersonModel in self.DataArr_Person)
    {
        if ([self.TempButton_Person.titleLabel.text isEqualToString:PersonModel.nickname])
        {
            PersonModelSub = PersonModel;
            break;
        }
    }
    [Cell SetGuiJuModel:Model PersonModel:PersonModelSub];
    Cell.ClickUpdate = ^(HNMainuUserListGuiJuModel *Model)
    {
        [self UpdateJiaFengOrJiaGuiWithModel:Model];
    };
    return Cell;
}


/** 修改家风或家规 */
- (void)UpdateJiaFengOrJiaGuiWithModel:(HNMainuUserListGuiJuModel *)Model
{
    UIAlertController *AlertController = [UIAlertController alertControllerWithTitle:@"修改" message:nil preferredStyle:(UIAlertControllerStyleAlert)];
    [AlertController addTextFieldWithConfigurationHandler:^(UITextField * _Nonnull textField) {
        textField.text = Model.content;
    }];
    [AlertController addAction:[UIAlertAction actionWithTitle:@"修改" style:(UIAlertActionStyleDestructive) handler:^(UIAlertAction * _Nonnull action) {

        UITextField *TextFile = [AlertController.textFields lastObject];
        [MBProgressHUD showHUD];
        NSDictionary *Params = @{
                                 @"id"     :Model.ID,
                                 @"content" :TextFile.text,
                                 @"action"   :@"updaterules"
                                 };

        [XDHttpTool SessPost:BaseURL(@"family.do") authCode:[AccountTool shareAccountTool].currentAccount.authCode params:Params success:^(id responseObj) {

            if (responseObj)
            {
                Model.content = TextFile.text;
                [self.TableView reloadData];

            }
            else
            {
                [MBProgressHUD showError:responseObj[@"msg"]];
            }
        } failure:^(NSError *error) {
            [MBProgressHUD showError:XDNetWorkError];
        }];
    }]];
    [AlertController addAction:[UIAlertAction actionWithTitle:@"取消" style:(UIAlertActionStyleCancel) handler:nil]];
    [self presentViewController:AlertController animated:YES completion:nil];
}







#pragma mark - Setter
- (UIScrollView *)ScrollView
{
    if (!_ScrollView)
    {
        _ScrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 16, 100, ScreenH-64-16)];
        _ScrollView.backgroundColor = [UIColor whiteColor];
    }
    return _ScrollView;
}

/** 人物Button */
- (UIButton *)GetLeftButtonWithTitle:(NSString *)Title Frame:(CGRect)Frame
{
    UIButton *Button = [UIButton buttonWithType:(UIButtonTypeCustom)];
    Button.frame = Frame;
    Button.titleLabel.font = [UIFont systemFontOfSize:14.f];
    [Button setTitle:Title forState:(UIControlStateNormal)];
    [Button setTitleColor:UIColorFromRGB(0x4c4c4c) forState:(UIControlStateNormal)];
    [Button setTitleColor:UIColor(255, 255, 255) forState:(UIControlStateSelected)];
    [Button setBackgroundImage:[self ImgForRGB:CGSizeMake(Frame.size.width, Frame.size.height) Color:[UIColor whiteColor]] forState:(UIControlStateNormal)];
    [Button setBackgroundImage:[self ImgForRGB:CGSizeMake(Frame.size.width, Frame.size.height) Color:ThemeColor] forState:(UIControlStateSelected)];
    UIView *View = [[UIView alloc] initWithFrame:CGRectMake(0, Button.frame.size.height-0.5, Button.frame.size.width, 0.5)];
    [Button addTarget:self action:@selector(SelectPerson:) forControlEvents:(UIControlEventTouchUpInside)];
    View.backgroundColor = UIColor(200, 200, 200);
    [Button addSubview:View];
    return Button;
    
}

//中国观、家风、家规view
- (UIView *)TopButtonView
{
    UIView *View = [[UIView alloc] initWithFrame:CGRectMake(self.ScrollView.frame.size.width,
                                                            self.ScrollView.frame.origin.y,
                                                            ScreenW-self.ScrollView.frame.size.width,
                                                            44)];
    View.backgroundColor = [UIColor whiteColor];
    for (int i=0; i<[[self TopGuiJu] count]; i++)
    {
        UIButton *Button = [self GetTopButtonWithTitle:[self TopGuiJu][i] Frame:CGRectMake(i*View.frame.size.width/3, 0, View.frame.size.width/3, View.frame.size.height)];
        [View addSubview:Button];
        if (i == 0)
        {
            self.TempButton_Top = Button;
            Button.selected = !Button.selected;
        }
    }
    return View;
    
}


- (UIButton *)GetTopButtonWithTitle:(NSString *)Title Frame:(CGRect)Frame
{
    UIButton *Button = [UIButton buttonWithType:(UIButtonTypeCustom)];
    Button.frame = Frame;
    Button.titleLabel.font = [UIFont systemFontOfSize:14.f];
    [Button setTitleColor:[UIColor whiteColor] forState:(UIControlStateNormal)];
    [Button setTitle:Title forState:(UIControlStateNormal)];
    [Button setBackgroundImage:[self ImgForRGB:CGSizeMake(Frame.size.width, Frame.size.height) Color:UIColor(140, 140, 140)] forState:(UIControlStateNormal)];
    [Button setBackgroundImage:[self ImgForRGB:CGSizeMake(Frame.size.width, Frame.size.height) Color:UIColor(252, 182, 22)] forState:(UIControlStateSelected)];
    [Button addTarget:self action:@selector(SelectGuiJu:) forControlEvents:(UIControlEventTouchUpInside)];
    Button.layer.cornerRadius = 5.0f;
    Button.layer.masksToBounds = YES;
    return Button;
}


- (NSArray *)TopGuiJu
{
    return @[@"中国规",@"家风",@"家规"];
}

- (NSMutableArray *)DataArr_Person
{
    if (!_DataArr_Person)
    {
        _DataArr_Person = [NSMutableArray array];
    }
    return _DataArr_Person;
}

- (NSMutableArray *)DataArr_GuiJu
{
    if (!_DataArr_GuiJu)
    {
        _DataArr_GuiJu = [NSMutableArray array];
    }
    return _DataArr_GuiJu;
}

- (UITableView *)TableView
{
    if (!_TableView)
    {
        _TableView = [[UITableView alloc] initWithFrame:CGRectMake(100, 16+44, ScreenW-100, ScreenH-64-16-44) style:(UITableViewStylePlain)];
        _TableView.tableFooterView = [UIView new];
        _TableView.tableHeaderView = [UIView new];
        _TableView.delegate = self;
        _TableView.dataSource = self;
        [_TableView registerNib:[UINib nibWithNibName:[HNMainUserListGuiJuCellTableViewCell description] bundle:nil] forCellReuseIdentifier:@"GuiJuCell"];
    }
    return _TableView;
}

- (UIButton *)AddGuiJuButton
{
    if (!_AddGuiJuButton)
    {
        _AddGuiJuButton = [UIButton buttonWithType:(UIButtonTypeCustom)];
        _AddGuiJuButton.frame = CGRectMake(self.TableView.frame.origin.x, ScreenH-44-16-44, self.TableView.frame.size.width, 44);
        [_AddGuiJuButton setTitle:@"添加" forState:(UIControlStateNormal)];
        [_AddGuiJuButton setBackgroundColor:ThemeColor];
        _AddGuiJuButton.titleLabel.font = [UIFont systemFontOfSize:14.f];
        [_AddGuiJuButton setTitleColor:[UIColor whiteColor] forState:(UIControlStateNormal)];
        [_AddGuiJuButton addTarget:self action:@selector(AddGuiJu:) forControlEvents:(UIControlEventTouchUpInside)];
        CGRect Rect = self.TableView.frame;
        Rect.size.height -= 44;
        self.TableView.frame = Rect;
    }
    return _AddGuiJuButton;
}

- (NSArray *)Type_GuiJu
{
    if (!_Type_GuiJu)
    {
        //Type=1 中国观   2为家风   3为家规
        _Type_GuiJu = @[@{@"name":@"中国规",@"type":@1},
                        @{@"name":@"家风",@"type":@2},
                        @{@"name":@"家规",@"type":@3}];
    }
    return _Type_GuiJu;
}
@end
